#!/bin/sh
#
# config -- Configure the common variables
#

# debug with DEBUG=1
[ x$DEBUG = x"1" ] && set -x

[ -z "$TOP_DIR" ] && TOP_DIR=$(cd $(dirname $0)/../../ && pwd)
TOP_DIR=$(cd $(dirname $TOP_DIR/null) && pwd)

# Basic variables
HOST_USER=$USER
[ "x$HOST_USER" = "xroot" -a -n "$SUDO_USER" ] && HOST_USER=$SUDO_USER

# Basic requirement: docker and let docker run without sudo
if [ ! -n "$IN_CONTAINER_CMD" ]; then
	DOCKER_INSTALL_CMD=$TOP_DIR/tools/docker/install
	$DOCKER_INSTALL_CMD >&2 || exit 1
	which groups >/dev/null 2>&1 && ((groups $HOST_USER | grep -q docker) || sudo usermod -aG docker $HOST_USER)
fi

[ -z "$TPROXY" ] && TPROXY=0

[ -z "$LAB_SECURITY" ] && LAB_SECURITY=0

# Variables need to pass to the container from our environment variables
VARS="UNIX_USER UNIX_PWD VNC_PWD VNC_PWD_VIEWONLY TPROXY VNC_SHARED SCREEN_SIZE HOST_NAME UNIX_IDENTIFY VNC_IDENTIFY SUDO_IDENTIFY VNC_IP VNC_TOKEN"

# Basic files/directories

LAB_HOST=$TOP_DIR/.host_name
LAB_OUTPUT=$TOP_DIR/output

GIT_DIR=$TOP_DIR/.git
GIT_WORKDIR=/.git

LAB_DIR=$TOP_DIR/labs
LAB_WORKDIR=/labs

TOOL_DIR=$TOP_DIR/tools
TOOL_WORKDIR=/tools

CONFIGS_DIR=$TOP_DIR/configs/
CONFIG_WORKDIR=/configs

# Some commands not require to specify the lab name
CMD=`basename $0`
echo "tproxy export choose unlock-all build-all pull-all git-pull-all push-all clean-all list release " | grep "$CMD "
[ $? -eq 0 ] && IGNORE_LAB_NAME=1

if [ -n "$IN_CONTAINER_CMD" ]; then
    LAB_DIR=$LAB_WORKDIR
    TOOL_DIR=$TOOL_WORKDIR
    CONFIG_DIR=$CONFIG_WORKDIR
else
    # Allow to pass lab name
    CURRENT=$1
    LAB_CURRENT=$LAB_DIR/.current_lab

    [ -n "$CURRENT" ] && ls $CONFIGS_DIR | tr -s ' ' | tr ' ' '\n' | grep -q ^$CURRENT$
    if [ $? -eq 1 -o -z "$CURRENT" ]; then
        CURRENT=""
        if [ -f $LAB_CURRENT ]; then
            CURRENT=$(cat $LAB_CURRENT)
            LAB_CURRENT_DIR=$LAB_DIR/$CURRENT
        fi
    fi

    # Container don't need this CURRENT
    [ -z "$CURRENT" -a -z "$IGNORE_LAB_NAME" ] && echo "LOG: Current lab not specified" >&2 && exit 1
    [ -n "$CURRENT" ] && echo "LOG: Current Lab is $CURRENT" >&2

    CONFIG_DIR=$TOP_DIR/configs/$CURRENT
fi

CORE_SYSTEM_DIR=$TOOL_DIR/system

CONFIG_TOOL_DIR=$CONFIG_DIR/tools
CONFIG_DOCKER_DIR=$CONFIG_DIR/docker
CONFIG_SYSTEM_DIR=$CONFIG_DIR/system

DOCKER_DIR=$TOOL_DIR/docker
DOCKER_IDENTIFY_CMD=$DOCKER_DIR/identify
DOCKER_VNC_CMD=$DOCKER_DIR/vnc
DOCKER_SSH_CMD=$DOCKER_DIR/ssh
DOCKER_WEBSSH_CMD=$DOCKER_DIR/webssh
DOCKER_EXPORT_CMD=$DOCKER_DIR/export
DOCKER_PUBLISH_CMD=$DOCKER_DIR/publish
DOCKER_TPROXY_CMD=$DOCKER_DIR/tproxy
DOCKER_CLEAN_CMD=$DOCKER_DIR/clean
DOCKER_RM_CMD=$DOCKER_DIR/rm
DOCKER_RUN_CMD=$DOCKER_DIR/run
DOCKER_UNLOCK_CMD=$DOCKER_DIR/unlock
DOCKER_FILE=$CONFIG_DIR/Dockerfile

# Common variables

LAB_IMAGE=$CONFIG_DOCKER_DIR/name
LAB_ENVS=$CONFIG_DOCKER_DIR/envs
LAB_CAPS=$CONFIG_DOCKER_DIR/caps
LAB_DEVICES=$CONFIG_DOCKER_DIR/devices
LAB_LIMITS=$CONFIG_DOCKER_DIR/limits
LAB_PORTMAP=$CONFIG_DOCKER_DIR/portmap
LAB_VOLUMEMAP=$CONFIG_DOCKER_DIR/volumemap

LAB_WEB_BROWSER=$CONFIG_DOCKER_DIR/.web_browser
LAB_CONTAINER_NAME=$CONFIG_DOCKER_DIR/.container_name
LAB_CONTAINER_ID=$CONFIG_DOCKER_DIR/.container_id
LAB_HOST_NAME=$CONFIG_DOCKER_DIR/.host_name
LAB_UNIX_USER=$CONFIG_DOCKER_DIR/.unix_user
LAB_UNIX_PWD=$CONFIG_DOCKER_DIR/.unix_pwd
LAB_UNIX_UID=$CONFIG_DOCKER_DIR/.unix_uid
LAB_VNC_PWD=$CONFIG_DOCKER_DIR/.vnc_pwd
LAB_VNC_PWD_VIEWONLY=$CONFIG_DOCKER_DIR/.vnc_pwd_viewonly
LAB_VNC_IP=$CONFIG_DOCKER_DIR/.vnc_ip
LAB_VNC_TOKEN=$CONFIG_DOCKER_DIR/.vnc_token
LAB_TPROXY=$CONFIG_DOCKER_DIR/.tproxy
LAB_SCREEN_SIZE=$CONFIG_DOCKER_DIR/.screen_size
LAB_VNC_SHARED=$CONFIG_DOCKER_DIR/.vnc_shared
LAB_VNC_IDENTIFY=$CONFIG_DOCKER_DIR/.vnc_identify
LAB_UNIX_IDENTIFY=$CONFIG_DOCKER_DIR/.unix_identify
LAB_SUDO_IDENTIFY=$CONFIG_DOCKER_DIR/.sudo_identify

[ `id -u` -ne 0 ] && SUDO=sudo

# Lock the important files for security
__do_lock ()
{
    # echo "LOG: __do_lock"

    $SUDO find $CONFIG_DOCKER_DIR -iname ".[^.]*" -exec chmod -f -R a-rw {} \;
    $SUDO chattr -R +i $CONFIGS_DIR
    $SUDO chattr -R +i $TOOL_DIR
}

# Unlock the important files for configuration
__do_unlock ()
{
    # echo "LOG: __do_unlock"

    $SUDO chattr -R -i $CONFIGS_DIR
    $SUDO chattr -R -i $TOOL_DIR
    $SUDO find $CONFIG_DOCKER_DIR -name ".[^.]*" -exec chmod -f -R 664 {} \;
}

do_lock ()
{
    [ $LAB_SECURITY -eq 1 ] && __do_lock
}

do_unlock ()
{
    [ $LAB_SECURITY -eq 1 ] && __do_unlock
}

# Variables initialization from config file if exist

LAB_VARS="IMAGE ENVS CAPS DEVICES LIMITS PORTMAP VOLUMEMAP"

LAB_VARS="$LAB_VARS WEB_BROWSER"
LAB_VARS="$LAB_VARS CONTAINER_NAME CONTAINER_ID HOST HOST_NAME"
LAB_VARS="$LAB_VARS UNIX_USER UNIX_PWD VNC_PWD VNC_PWD_VIEWONLY TPROXY UNIX_UID UNIX_IDENTIFY VNC_IDENTIFY SUDO_IDENTIFY VNC_IP VNC_TOKEN"
LAB_VARS="$LAB_VARS VNC_SHARED SCREEN_SIZE"

do_unlock

# Prefer user input to the one saved in config file

for VAR in $LAB_VARS
do
    var_file=`eval echo \\${LAB_$VAR}`
    # Accesspt ENV
    var=`eval echo \\$${VAR}`

    # echo $VAR $var
    # echo "LOG: Get $VAR from $var_file"

    var_value=""
    [ -n "$var_file" -a -f "$var_file" -a -z "$var" ] && var_value='$(grep -v "#" $var_file)' && eval `eval echo \\$VAR='$var_value'`

    echo `eval echo "LOG: $VAR=\\$${VAR}"`
done

do_lock

# Control the password complexity
DEF_PWD_LENGTH=6
DEF_TOKEN_LENGTH=6
DEF_PWD_TOTAL=100
[ -z "$TOKEN_LENGTH" ] && TOKEN_LENGTH=$DEF_TOKEN_LENGTH

DEF_TOKEN_DIR=.vnc-tokens
DEF_VNC_IP="0.0.0.0"
DEF_ENCRYPT_CMD=md5sum
[ -z "$ENCRYPT_CMD" ] && ENCRYPT_CMD=$DEF_ENCRYPT_CMD

DEF_SCREEN_SIZE=1280x800

if [ $LAB_SECURITY -eq 1 ]; then
    WEB_NOSSL=0
    WEB_ENCRYPT=1
    WEB_HTTP=https
    # Account password locked, forbid the identify
    DEF_UNIX_IDENTIFY=0
    # No sudo, no way to switch to root in clients
    DEF_SUDO_IDENTIFY=0
    [ -z "$VNC_SHARED" ] && VNC_SHARED=0
else
    WEB_NOSSL=1
    WEB_ENCRYPT=0
    WEB_HTTP=http
    # Not locked
    DEF_UNIX_IDENTIFY=1
    # Can get root simply with sudo
    DEF_SUDO_IDENTIFY=1
    [ -z "$VNC_SHARED" ] && VNC_SHARED=1
fi

# 16:10: 640x480 800x480 1280x800 1440x900 1680x1050 1920x1200 2560x1600
# 16:9: 960x540 1280x720 1920x1080 2560x1440
which xrandr >/dev/null 2>&1
[ $? -eq 0 -a -z "$SCREEN_SIZE" ] && SCREEN_SIZE=`xrandr --current | grep "^ .*\*" | tr -s ' ' | cut -d' ' -f2 | head -1`

[ -z "$SCREEN_SIZE" ] && SCREEN_SIZE=$DEF_SCREEN_SIZE

if [ -z "$IMAGE" ]; then
    # Fixme: It is not possible to run here.
    IMAGE=tinylab/$CURRENT
fi

LAB_USER=`dirname $IMAGE`
LAB_NAME=$CURRENT

# More variables

IMAGES=`find $CONFIGS_DIR -name "name" | xargs -i cat {} | sort -u`
LABS=`find ${LAB_DIR} -maxdepth 1 -mindepth 1 -type d | xargs -i basename {}`

LOCAL_DESKTOP_SHORTCUT=~/Desktop/${CONTAINER_NAME}.desktop
[ -d $CONFIG_SYSTEM_DIR ] \
  && REMOTE_DESKTOP_SHORTCUT=`find $CONFIG_SYSTEM_DIR -maxdepth 4 -name "lab.desktop"`

CONTAINER_VNC_PORT=6080
CONTAINER_SSH_PORT=22
CONTAINER_WEBSSH_PORT=443
[ -z "$HOST_VNC_PORT" ] && HOST_VNC_PORT=6080
[ -z "$HOST_SSH_PORT" ] && HOST_SSH_PORT=2222
[ -z "$HOST_WEBSSH_PORT" ] && HOST_WEBSSH_PORT=4433

LAB_HOST_RUN=$CONFIG_TOOL_DIR/host-run
LAB_CONTAINER_RUN=$CONFIG_TOOL_DIR/container-run

# Common functions

get_var () #VAR #defval
{
    local var_value
    local VAR
    local defval

    VAR=$1
    defval=$2

    var_file=`eval echo \\${LAB_$VAR}`
    var_value=""

    [ -n "$var_file" -a -f "$var_file" ] && var_value='$(cat $var_file)' && eval `eval echo \\$VAR='$var_value'`
    [ -z "$var_value" ] && eval `eval echo \\$VAR=$defval`

    #echo `eval echo "LOG: GET: $VAR=\\$${VAR}"`
}

set_var () #VAR
{
    local VAR
    local var
    local var_file

    VAR=$1

    var=`eval echo \\$${VAR} | egrep -v "^$|^ *$"`
    var_file=`eval echo \\${LAB_$VAR}`

    #echo "LOG: SET: Save '$var' to $var_file"

    if [ -n "$var" ]; then
	echo "$var" | tr ' ' '\n' > $var_file
    fi
}

do_op () #op $ARG $args
{
    local op
    local ARG
    local arg
    local args

    op=$1
    ARG=$2
    args=$3

    arg=`eval echo \\$${ARG}`

    [ -z "$arg" ] && echo "LOG: '$ARG' required for '$op'" && exit 1

    echo "LOG: Running ' $op $arg $args'"

    eval $op $arg $args
}

get_random ()
{
    random=$RANDOM
    if [ -n "$random" ]; then
        echo $random
    else
        random=`date '+%s'`
        echo $(( random % 32767 ))
    fi
}
